/**
 * 
 */
package util;

import java.lang.reflect.Array;

/**
 * Class conaining static array conactonation utilities.
 * 
 * @author Joshua Lockerman
 *
 */
public class ArrayConcat {
    /**
     * Concatenates a number of arrays in order into an array whose length is
     * equal to the sum of the lengths of the arrays. The method skips null arrays
     * as long as there is at least one non null array in arrays. If arrays itself
     * is null this method will throw a NullPointerException
     * @param <T> the type of array that is being concatenated.
     * @param arrays the arrays to be concatenated.
     * @return an array containing the elements of the inputed arrays in order of input.
     */
    @SuppressWarnings("unchecked")
    public static <T> T[] concatenate(T[]... arrays)
    {
        int length = 0;
        for(int i = 0; i < arrays.length; i++) {
            if(arrays[i] != null) {
                length += arrays[i].length;
            }
        }
        
        Class<?> type = arrays.getClass().getComponentType().getComponentType();
        T[] concatArray = (T[]) Array.newInstance(type, length);
        int index = 0;
        for(int i = 0; i < arrays.length; i++) {
            if(arrays[i] != null) {
                for(int j = 0; j < arrays[i].length; j++) {
                    concatArray[index] = arrays[i][j];
                    index++;
                }
            }
        }
        return concatArray;
    }
}
